﻿using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SilverlightViewport.Common;

namespace SilverlightViewport.XNA
{
	public class XnaSilverlightComponent : DrawableGameComponent
	{
        private SilverlightWindowless _mSilverlightWindowless;
		private byte[] _byteArray;
		private SpriteBatch _spriteBatch;
		private MouseState _lastMouseState;

		public Vector2 Size;
		public Vector2 Position;
		public Texture2D Texture { get; set; }
		public string BaseUrl;
		public string Source;

		public XnaSilverlightComponent(Game game) : base(game)
		{
		}

		public override void Initialize()
		{
			base.Initialize();

			_spriteBatch = new SpriteBatch(this.GraphicsDevice);
			Texture = new Texture2D(this.GraphicsDevice, (int)Size.X, (int)Size.Y);

             _mSilverlightWindowless = new SilverlightWindowless();
             _mSilverlightWindowless.Width = (int)Size.X;
             _mSilverlightWindowless.Height = (int)Size.Y;
             _mSilverlightWindowless.BaseUrl = BaseUrl;
             _mSilverlightWindowless.Source = Source;
             _mSilverlightWindowless.RenderFps = 0;

             /* The on rendered event informs us when a new frame has been rendered
              * and is ready for presentation */
			 _mSilverlightWindowless.OnRendered += SilverlightWindowless_OnRendered;
		}

		void SilverlightWindowless_OnRendered(object sender, RenderedFrameEventArgs e)
		{
			if(_byteArray == null)
				_byteArray = new byte[e.BufferSize];

            if (_byteArray.Length != e.BufferSize)
                _byteArray = new byte[e.BufferSize];

			Marshal.Copy(e.Buffer, _byteArray, 0, e.BufferSize);
			Texture.SetData(_byteArray);
		}

		public override void Update(GameTime gameTime)
		{
			base.Update(gameTime);

			_mSilverlightWindowless.Render();

			MouseState ms = Mouse.GetState();
			double x = ms.X / Size.X;
			double y = ms.Y / Size.Y;

			if(ms.LeftButton == ButtonState.Pressed && _lastMouseState.LeftButton == ButtonState.Released)
				_mSilverlightWindowless.SendLeftButtonDown(x, y);
			if(ms.LeftButton == ButtonState.Released && _lastMouseState.LeftButton == ButtonState.Pressed)
				_mSilverlightWindowless.SendLeftButtonUp(x, y);
			_mSilverlightWindowless.SendMouseMove(x, y);
			//_mSilverlightWindowless.SendScroll(ms.ScrollWheelValue);

			_lastMouseState = ms;
		}

		public override void Draw(GameTime gameTime)
		{
			base.Draw(gameTime);

			_spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
			    _spriteBatch.Draw(Texture, Position, Color.White);
			_spriteBatch.End();
		}
	}
}
